package com.demo.agent;

import com.demo.agent.manager.RegistryManager;
import com.demo.agent.tool.ToolServiceImpl;

import java.lang.instrument.Instrumentation;
import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

/**
 * @author: huangjiazhen
 * @create: 2023/11/20 19:58
 * @description:    附着启动
 **/
public class MyAgent {

    public static Instrumentation instrumentation;

    private static ToolServiceImpl service;



    public static void agentmain(String args, Instrumentation instrumentation) {
        System.out.println("hello agentmain!");
        MyAgent.instrumentation = instrumentation;
        try {
            startRmiService(9527);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    private static void startRmiService(int port) throws RemoteException, MalformedURLException, AlreadyBoundException, NotBoundException {
        service = new ToolServiceImpl();
        System.out.println("==========service: " + service);
        Registry registry = LocateRegistry.createRegistry(port);
        System.out.println("==========registry: " + registry);
        RegistryManager.save(port, registry);
        Naming.bind("rmi://localhost:9527/toolService", service);

//        registry.bind("rmi://localhost:9527/toolService", service);
        System.out.println("lookup: " + Naming.lookup("rmi://localhost:9527/toolService"));
        System.out.println("rmi 已启动：" + port);
    }
}
